/**
 * Created by ajhin on 3/6/2015.
 */
package com.societyGames.flashForms
{
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.events.Event;
import flash.text.TextField;

public class TextOverDisplayObject extends Sprite
{
  private var _desiredHeight:Number;
  private var _desiredWidth:Number;
  private var _textField:TextField;
  private var _displayObject:DisplayObject;

  public function TextOverDisplayObject(displayObject:DisplayObject, textField:TextField)
  {
    _displayObject = displayObject;
    addChild(_displayObject);

    this._textField = textField;
    addChild(this._textField);
    if (textField is DynamicTextField)
    {
      DynamicTextField(textField).sizeChangedEventObject.addEventListener(textFieldSizeChangedHandler);
    }

    this._desiredWidth = _displayObject.width;
    this._desiredHeight = _displayObject.height;
    recalculate();
  }

  private function textFieldSizeChangedHandler(event:Event):void
  {
    recalculate();
  }

  public function get textField():TextField
  {
    return this._textField;
  }

  private function recalculate():void
  {
    recalculateWidth();
    recalculateHeight();
  }

  private function recalculateWidth():void
  {
    this._displayObject.width = this._desiredWidth;
    this._textField.width = this._desiredWidth;
  }

  private function recalculateHeight():void
  {
    this._displayObject.height = this._desiredHeight;
    textField.height = Math.min(this._desiredHeight, _textField.height = _textField.numLines * _textField.textHeight + 4);
    textField.y = (this._desiredHeight - textField.height) / 2;
  }

  override public function set height(value:Number):void
  {
    if (value != this._desiredHeight)
    {
      this._desiredHeight = value;
      recalculateHeight();
    }
  }

  override public function set width(value:Number):void
  {
    if (value != _desiredWidth)
    {
      _desiredWidth = value;
      recalculateWidth();
    }
  }
}
}
